package com.homework.news

import android.app.Activity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class NewsAdapter(activity: Activity, val resourceId: Int, data: List<News>) :
    ArrayAdapter<News>(activity, resourceId, data) {

    inner class ViewHolder(
        val title: TextView,
        val img1: ImageView,
        val img2: ImageView,
        val img3: ImageView,
        val author: TextView,
        val date: TextView
    )

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val viewHolder: ViewHolder
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(resourceId, parent, false)
            val title: TextView = view.findViewById(R.id.title)
            val img1: ImageView = view.findViewById(R.id.img1)
            val img2: ImageView = view.findViewById(R.id.img2)
            val img3: ImageView = view.findViewById(R.id.img3)
            val author: TextView = view.findViewById(R.id.author)
            val date: TextView = view.findViewById(R.id.date)
            viewHolder = ViewHolder(title, img1, img2, img3, author, date)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        val news = getItem(position)
        if (news != null) {
            Log.i("NewsAdapter:", "开始注入数据...")
            viewHolder.title.text = news.title
            Glide.with(context).load(news.thumbnail_pic_s).into(viewHolder.img1);
            Glide.with(context).load(news.thumbnail_pic_s02).into(viewHolder.img2);
            Glide.with(context).load(news.thumbnail_pic_s03).into(viewHolder.img3);
            viewHolder.author.text = news.author_name
            viewHolder.date.text = news.date
        } else {
            Log.i("NewsAdapter:", "未接收到数据!")
        }
        return view
    }
}